
<template>
  <view class="wrap">
    <u-form :model="model" :rules="rules" ref="uForm" :errorType="errorType">
      <u-form-item
        :leftIconStyle="{ color: '#888', fontSize: '32rpx' }"
        left-icon="account"
        label-width="120"
        :label-position="labelPosition"
        label="姓名"
        prop="name"
      >
        <u-input
          :border="border"
          placeholder="请输入姓名"
          v-model="model.name"
          type="text"
        ></u-input>
      </u-form-item>
      <u-form-item :label-position="labelPosition" label="性别" prop="sex">
        <u-input
          :border="border"
          type="select"
          :select-open="actionSheetShow"
          v-model="model.sex"
          placeholder="请选择性别"
          @click="actionSheetShow = true"
        ></u-input>
      </u-form-item>
      <u-form-item :label-position="labelPosition" label="简介" prop="intro">
        <u-input
          type="textarea"
          :border="border"
          placeholder="请填写简介"
          v-model="model.intro"
        />
      </u-form-item>
      <u-form-item
        :label-position="labelPosition"
        label="上传头像"
        prop="photo"
        label-width="150"
      >
        <u-upload
          width="160"
          height="160"
          ref="uUpload"
          :auto-upload="false"
          @on-choose-complete="onChooseComplete1"
        ></u-upload>
      </u-form-item>
      <u-form-item
        :label-position="labelPosition"
        label="上传背景图片"
        prop="photo2"
        label-width="150"
      >
        <u-upload
          width="160"
          height="160"
          ref="uUpload"
          :auto-upload="false"
          @on-choose-complete="onChooseComplete2"
        ></u-upload>
      </u-form-item>
    </u-form>
    <view class="agreement">
      <u-checkbox v-model="check" @change="checkboxChange"></u-checkbox>
      <view class="agreement-text"> 勾选代表同意美食手册的隐私协议 </view>
    </view>
    <u-button @click="submit">提交</u-button>
    <u-action-sheet
      :list="actionSheetList"
      v-model="actionSheetShow"
      @click="actionSheetCallback"
    ></u-action-sheet>
    <u-select
      mode="single-column"
      :list="selectList"
      v-model="selectShow"
      @confirm="selectConfirm"
    ></u-select>
  </view>
</template>

<script>
export default {
  data() {
    let that = this;
    return {
      // 统一路径
      urlHeat3: "", // https://fine-food.xiamu.icu
      // urlHeat3: "http://localhost:8080",
      //表单信息
      model: {
        name: "",
        sex: "",
        intro: "",
        agreement: false,
        photo: "",
        photo2: "",
      },
      //用户id
      userId: 0,
      userAvatar: "",
      userBackground: "",
      selectList: [],
      rules: {
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 5,
            message: "姓名长度在3到5个字符",
            trigger: ["change", "blur"],
          },
          {
            // 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
            validator: (rule, value, callback) => {
              // 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
              return this.$u.test.chinese(value);
            },
            message: "姓名必须为中文",
            // 触发器可以同时用blur和change，二者之间用英文逗号隔开
            trigger: ["change", "blur"],
          },
          // 异步验证，用途：比如用户注册时输入完账号，后端检查账号是否已存在
          // {
          // 	trigger: ['blur'],
          // 	// 异步验证需要通过调用callback()，并且在里面抛出new Error()
          // 	// 抛出的内容为需要提示的信息，和其他方式的message属性的提示一样
          // 	asyncValidator: (rule, value, callback) => {
          // 		this.$u.post('/ebapi/public_api/index').then(res => {
          // 			// 如果验证出错，需要在callback()抛出new Error('错误提示信息')
          // 			if(res.error) {
          // 				callback(new Error('姓名重复'));
          // 			} else {
          // 				// 如果没有错误，也要执行callback()回调
          // 				callback();
          // 			}
          // 		})
          // 	},
          // }
        ],
        sex: [
          {
            required: true,
            message: "请选择性别",
            trigger: "change",
          },
        ],
        intro: [
          {
            required: true,
            message: "请填写简介",
          },
          {
            min: 5,
            message: "简介不能少于5个字",
            trigger: "change",
          },
          // 正则校验示例，此处用正则校验是否中文，此处仅为示例，因为uView有this.$u.test.chinese可以判断是否中文
          {
            pattern: /^[\u4e00-\u9fa5]+$/gi,
            message: "简介只能为中文",
            trigger: "change",
          },
        ],
      },
      border: false,
      check: false,
      actionSheetList: [
        {
          text: "男",
        },
        {
          text: "女",
        },
        {
          text: "保密",
        },
      ],
      actionSheetShow: false,
      selectShow: false,
      radioCheckWidth: "auto",
      labelPosition: "left",
      errorType: ["message"],
      code: "",
    };
  },
  onLoad() {
    const { hostname } = this.$store.state.moduleCommon;
		this.urlHeat3 = hostname;
    //获得用户信息
    uni.request({
      url: this.urlHeat3 + "/api/users/getUsers", //
      method: "POST",

      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: "Bearer " + uni.getStorageSync("Authorization"),
      },
      success: (res) => {
        console.log("用户信息", res);
        this.userId = res.data.data.userId;
        this.model.name = res.data.data.userName;
        this.model.sex = res.data.data.userSex;
        this.model.intro = res.data.data.userIntroduce;
        this.userAvatar = res.data.data.userAvatar;
        this.userBackground = res.data.data.userBackground;
      },
    });
  },
  computed: {},
  onReady() {},
  methods: {
    //上传图像
    onChooseComplete1(chooseImageRes) {
      console.log(chooseImageRes);
      uni.uploadFile({
        url: this.urlHeat3 + "/api/users/file",
        filePath: chooseImageRes[0].file.path,
        name: "file",
        formData: {
          userId: this.userId,
          type: "userAvatar",
        },
        success: (uploadFileRes) => {
          console.log("userAvatar", JSON.parse(uploadFileRes.data));
          this.userAvatar = JSON.parse(uploadFileRes.data).data;
        },
      });
    },
    onChooseComplete2(chooseImageRes) {
      console.log(chooseImageRes);
      uni.uploadFile({
        url: this.urlHeat3 + "/api/users/file",
        filePath: chooseImageRes[0].file.path,
        name: "file",
        formData: {
          userId: this.userId,
          type: "userBackground",
        },
        success: (uploadFileRes) => {
          console.log("userBackground", JSON.parse(uploadFileRes.data));
          this.userBackground = JSON.parse(uploadFileRes.data).data;
        },
      });
    },
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (!this.model.agreement) return this.$u.toast("请勾选协议");
          console.log("验证通过");
          console.log(this.model);
          //修改用户信息
          uni.request({
            url: this.urlHeat3 + "/api/users/updataUsers", //
            method: "POST",
            data: {
              userId: this.userId,
              userName: this.model.name,
              userSex: this.model.sex,
              userIntroduce: this.model.intro,
              userAvatar: this.userAvatar,
              userBackground: this.userBackground,
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            success: (res) => {
              console.log("修改用户信息", res);

              uni.switchTab({
                url: "/pages/individual/individual",
              });
            },
          });
        } else {
          console.log("验证失败");
        }
      });
    },
    // 点击actionSheet回调
    actionSheetCallback(index) {
      uni.hideKeyboard();
      this.model.sex = this.actionSheetList[index].text;
    },
    // 勾选版权协议
    checkboxChange(e) {
      this.model.agreement = e.value;
    },
    errorChange(index) {
      if (index == 0) this.errorType = ["message"];
      if (index == 1) this.errorType = ["toast"];
      if (index == 2) this.errorType = ["border-bottom"];
      if (index == 3) this.errorType = ["border"];
    },
  },
};
</script>

<style scoped lang="scss">
.wrap {
  padding: 30rpx;
}

.agreement {
  display: flex;
  align-items: center;
  margin: 40rpx 0;

  .agreement-text {
    padding-left: 8rpx;
    color: $u-tips-color;
  }
}
</style>

